package com.oocl.scan.handler;

import com.oocl.scan.dao.SoapConfigDao;
import com.oocl.scan.dao.impl.SoapConfigDaoImpl;
import com.oocl.scan.jdt.parser.ModifierParser;
import com.oocl.scan.model.JavaClassElement;
import com.oocl.scan.model.SoapConfig;
import com.oocl.scan.utils.ScanConstants;
import com.oocl.scan.utils.StringUtil;
import java.util.List;
import org.eclipse.jdt.core.dom.SingleMemberAnnotation;

public class SoapConfigHandler extends BaseHandler{

  @Override
  public void handle(JavaClassElement element) {
    if (StringUtil.isNotEmpty(element.getParent()) && element.getParent().contains(ScanConstants.RESTFUL_PARENT_CLASS)) {
      SingleMemberAnnotation pathAnnotation = ModifierParser.getSingleMemberAnnotation(element.getTypeDeclaration(), ScanConstants.ANNOTATION_REST_PATH);
      if (pathAnnotation != null && element.getParent().contains("<")) {
        SoapConfigDao dao = new SoapConfigDaoImpl();
        List<SoapConfig> soapConfigList = dao.getAllOrigin();
        String dtoInResource = element.getParent().substring(element.getParent().indexOf("<") + 1, element.getParent().indexOf(">"));
        String subUrl = pathAnnotation.getValue().toString().substring(2, pathAnnotation.getValue().toString().length() - 1);
        String resourceClassName = element.getJavaClassFullName();
        String moduleName = element.getModuleName().toLowerCase();
        SoapConfig soapConfig = getSoapConfig(moduleName, subUrl, dtoInResource, resourceClassName, soapConfigList);
        if (soapConfig != null) {
          dao.add(soapConfig);
        }
      }
    }
  }

  private static SoapConfig getSoapConfig(String moduleName, String subURL, String dtoInResource, String resourceClassName, List<SoapConfig> soapConfigList) {
    for (SoapConfig soapConfig : soapConfigList) {
      if (soapConfig.getSoapConfigURL().contains(moduleName) && soapConfig.getDtoName().endsWith(dtoInResource) && soapConfig.isOrigin()) {
        if (soapConfig.getSoapConfigURL().endsWith(subURL)) {
          SoapConfig soap = soapConfig;
          soap.setResourceName(resourceClassName);
          return soap;
        }
        if (StringUtil.isEmpty(soapConfig.getResourceName())) {
          SoapConfig soap = new SoapConfig();
          soap.setResourceName(resourceClassName);
          soap.setDtoName(soapConfig.getDtoName());
          soap.setSoapConfigURL(soapConfig.getSoapConfigURL() + getSubURL(soapConfig.getSoapConfigURL(), subURL));
          soap.setOrigin(false);
          return soap;
        }
      }
    }
    return null;
  }

  private static String getSubURL(String originStr, String subStr) {
    for (int i = subStr.length() - 1; i > 0; i--) {
      if (originStr.contains(subStr.substring(0, i))) {
        return subStr.substring(i, subStr.length());
      }
    }
    return null;
  }
}
